import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      path: "/",
      name: "layoutPage",
      redirect: "/homePage",
      component: () => import("@/views/Layout/layoutPage.vue"),
      children: [
        {
          path: "/homePage",
          name: "homePage",
          component: () => import("@/views/Layout/homePage.vue"),
        },
        {
          path: "/cartPage",
          name: "cartPage",
          component: () => import("@/views/Layout/cartPage.vue"),
        },
        {
          path: "/caterlogPage",
          name: "caterlogPage",
          component: () => import("@/views/Layout/caterlogPage.vue"),
        },
        {
          path: "/userPage",
          name: "userPage",
          component: () => import("@/views/Layout/userPage.vue"),
        },
      ],
    },
    {
      path: "/loginPage",
      name: "loginPage",
      component: () => import("@/views/login/loginPage.vue"),
    },
    {
      path: "/orderPage",
      name: "orderPage",
      component: () => import("@/views/orderMgr/orderPage.vue"),
    },
    {
      path: "/payPage",
      name: "payPage",
      component: () => import("@/views/pay/payPage.vue"),
    },
    {
      path: "/productDetailPage/:id", //动态id
      name: "productDetailPage",
      component: () => import("@/views/productDetail/productDetailPage.vue"),
    },
    {
      path: "/searchPage",
      name: "searchPage",
      component: () => import("@/views/Search/searchPage.vue"),
    },
    {
      path: "/searchListPage",
      name: "searchListPage",
      component: () => import("@/views/Search/searchListPage.vue"),
    },
  ],
});

const authPages = ["/orderPage", "/payPage"];

// 路由守卫
// to: 即将要访问的路径
// from: 即将要离开的路径
// next: 是否放行 是一个方法
// next() 放行  如果不写next() 则默认阻断
// next({path:'/loginPage'}) 跳转到指定页面
router.beforeEach((to, from, next) => {
  if (authPages.includes(to.path)) {
    // 判断是否登录
    if (!localStorage.getItem("token")) {
      next({ path: "/loginPage" });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
